package rc.database.JarDuomenys;

/**
 * Created by IntelliJ IDEA.
 * User: Slejus
 * Date: 13.6.11
 * Time: 13.14
 * To change this template use File | Settings | File Templates.
 */

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.extensions.webscripts.AbstractWebScript;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;
import rc.database.connection.DBOperations;

import java.io.IOException;
import java.sql.*;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JarDuomenysWebScript extends AbstractWebScript {

    private static final String[] codes = {
            "124110246", "147025577", "135040952", "140042759", "144126368",
            "183607488", "149952323", "179204613", "180101069", "124208338"
    };

    private final String KOD = "Kodas";
    private final String PAV = "Pavadinimas";
    private final String FID = "FilialoId";
    private final String FPAV = "FilialoPav";
    private final String DEPID = "PadalinioId";
    private final String DEPPAV = "PadalinioPav";
    private final String DID = "PADN_ID";
    private final String DPAV = "PADN_PAV";

    public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        ResultSet res2 = null;
        String code;
        String type;
        boolean branch = false;

        try {
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath:alfresco/extension/connection-context.xml");
            DBOperations db = (DBOperations)context.getBean("dbOperations");
            code = req.getParameter("code");
            type = req.getParameter("type");
            if (isNumeric(code)) {
                if (type.equals("jar") && code != null && code.length() > 4) {
                    Class.forName(db.getJdbcDriver());
                    conn = DriverManager.getConnection(db.getJdbcUrl(), db.getUsername(), db.getPassword());
                    conn.setAutoCommit(false);
                    stmt = conn.createStatement();
                    rs = stmt.executeQuery(db.getJar2Query(code));
                    JSONObject obj = new JSONObject();
                    if (rs.next()) {
                        obj = db.appendTwoStrings(obj, rs, KOD, PAV, KOD.toUpperCase(), PAV.toUpperCase());
                        while (rs.next()) {
                            obj = db.appendTwoStrings(obj, rs, KOD, PAV, KOD.toUpperCase(), PAV.toUpperCase());
                        }
                        for (int i = 0; i < codes.length; i++) {
                            if (code.equals(codes[i])) {
                                branch = true;
                                res2 = stmt.executeQuery(db.getBranchesQuery());
                                obj = db.appendRsJSONData(obj, res2, FID, FPAV, DID, DPAV);
                                res2.close();
                                break;
                            }
                        }
                        if (branch == false) {
                            obj = db.appendTwoStrings(obj, FID, FPAV, "None");
                        }
                    } else {
                        obj = db.appendTwoStrings(obj, KOD, PAV, "None");
                        obj = db.appendTwoStrings(obj, FID, FPAV, "None");
                    }
                    String jsonString = obj.toString();
                    res.setContentType("application/json; charset=utf-8");
                    res.getWriter().write(jsonString);

                } else if (type.equals("rc") && code != null && code.length() > 1) {
                    Class.forName(db.getJdbcDriver());
                    conn = DriverManager.getConnection(db.getJdbcUrl(), db.getUsername(), db.getPassword());
                    conn.setAutoCommit(false);
                    stmt = conn.createStatement();
                    rs = stmt.executeQuery(db.getDepartmentsQuery(code));
                    JSONObject obj = new JSONObject();
                    if (rs.next()) {
                        obj = db.appendTwoStrings(obj, rs, DEPID, DEPPAV, DID, DPAV);
                        while (rs.next()) {
                            obj = db.appendTwoStrings(obj, rs, DEPID, DEPPAV, DID, DPAV);
                        }
                    } else {
                        obj = db.appendTwoStrings(obj, DEPID, DEPPAV, "None");
                    }
                    obj = db.appendTwoStrings(obj, KOD, PAV, "set");
                    String jsonString = obj.toString();
                    res.setContentType("application/json; charset=utf-8");
                    res.getWriter().write(jsonString);
                } else {
                    badRequest(db, res);
                }
            } else {
                badRequest(db, res);
            }
        } catch (JSONException ex) {
            Logger.getLogger(JarDuomenysWebScript.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(JarDuomenysWebScript.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JarDuomenysWebScript.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    Logger.getLogger(JarDuomenysWebScript.class.getName()).log(Level.SEVERE, null, e);
                }
            }
            if (res2 != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    Logger.getLogger(JarDuomenysWebScript.class.getName()).log(Level.SEVERE, null, e);
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    Logger.getLogger(JarDuomenysWebScript.class.getName()).log(Level.SEVERE, null, e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.getLogger(JarDuomenysWebScript.class.getName()).log(Level.SEVERE, null, e);
                }
            }
        }
    }

    private static boolean isNumeric(String str) {
        NumberFormat formatter = NumberFormat.getInstance();
        ParsePosition pos = new ParsePosition(0);
        formatter.parse(str, pos);
        return str.length() == pos.getIndex();
    }

    private void badRequest(DBOperations dbObj, WebScriptResponse response) throws JSONException, IOException {
        JSONObject obj = new JSONObject();
        obj = dbObj.appendTwoStrings(obj, KOD, PAV, "None");
        String jsonString = obj.toString();
        response.getWriter().write(jsonString);
    }
}